package JavaUtils.web;

import JavaUtils.CSUtils.Log.CLog;

import java.net.URLDecoder;
import java.util.*;

public class ReqInfo {
    static final String tag = "ReqInfo";
    public static final String cDataTypeTxt = "txt";
    public static final String cDataTypeBytes = "blob";
    public static final String cDataTypeJson = "json";
    public static final String cDataTypeFormData = "formData";
    //
    public String requestType;
    public String url;
    public String fileName;
    //
    public String handerStr;
    public String[] handerStrArr;
    public int handEndPos;
    public Map<String, String> headerMap = new HashMap<>();
    //
    public Map<String, String> dataMap = new HashMap<>();
    public List<byte[]> dataBytesList = new ArrayList<>();
    public String postDataType;
    public String dataStr;
    public long contentLength;


    public int resp_state = 200;
    public String resp_txt;
    public byte[] resp_bytes;

    public static Boolean GetHanderData(String handerStr, ReqInfo reqInfo) {
        try {
            handerStr = URLDecoder.decode(handerStr, "utf-8");
        } catch (Exception ignored) { }
        reqInfo.handerStrArr = handerStr.split("\r\n");
        String[] split = reqInfo.handerStrArr[0].split(" ");
        if (split.length != 3) {
            CLog.ex(tag, "http头解析错误......." + handerStr);
            return false;
        }
        reqInfo.requestType = split[0].toLowerCase();
        reqInfo.url = split[1];
        String[] urlData = reqInfo.url.split("[?]");
        reqInfo.fileName = urlData[0].trim();

        reqInfo.dataMap = new HashMap<>();
        if (urlData.length > 1) {
            String[] keyValueArr = urlData[1].split("[&]");
            for (String keyValue : keyValueArr) {
                String[] _data = keyValue.split("[=]");
                if (_data.length >= 2) {
                    reqInfo.dataMap.put(_data[0].trim(), _data[1].trim());
                }
            }
        }
        for (int i = 1; i < reqInfo.handerStrArr.length; i++) {
            String[] keyValueArr = reqInfo.handerStrArr[i].split(":");
            if (keyValueArr.length >= 2) {
                reqInfo.headerMap.put(keyValueArr[0].trim(), keyValueArr[1].trim());
            }
        }
        CLog.e(tag, "web头数据获取完成...url=" + reqInfo.url);
        return true;
    }

    @Override
    public String toString() {
        String log = fileName;
        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
            log += "__" + entry.getKey() + "=" + entry.getValue();
        }
        return log;
    }
}
